package io.virtualapp.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import io.virtualapp.R;
import io.virtualapp.VCommends;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.GetNewBean;
import io.virtualapp.bean.NumBean;
import io.virtualapp.bean.Swt;
import io.virtualapp.home.adapters.TabFragmentPagerAdapter;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.http.HttpUtils;
import io.virtualapp.mylibrary.util.SpUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import io.virtualapp.widgets.DialogDownLoadAPK;
import okhttp3.Request;
import okhttp3.Response;
import zxing.MainActivity;
import zxing.android.CaptureActivity;

public class IndexMainActivity extends VActivity implements View.OnClickListener {
    @BindView(R.id.myViewpager)
    ViewPager myViewpager;
    @BindView(R.id.img_zhizuo)
    ImageView imgZhizuo;
    @BindView(R.id.rv_zhizuo)
    RelativeLayout rvZhizuo;

    @BindView(R.id.rv_shenqi)
    RelativeLayout rvShenqi;
    @BindView(R.id.bottomly)
    LinearLayout bottomly;
    @BindView(R.id.txtz_zhizuo)
    TextView txtzZhizuo;
    @BindView(R.id.txt_shenqi)
    TextView txtShenqi;
    @BindView(R.id.img_center)
    ImageView imgCenter;
    @BindView(R.id.txt_center)
    TextView txtCenter;
    @BindView(R.id.rv_center)
    RelativeLayout rvCenter;
    private List<Fragment> list;
    private TabFragmentPagerAdapter adapter;
    private boolean isFirstInApp;
    private long surplus;//剩余时间
    private long exitTime = 0;
    private RxPermissions rxPermissions;
    String[] PERMISSIONS = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    public static void goHome(Context context) {
        Intent intent = new Intent(context, IndexMainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index_main);
        //检测是否有写的权限
        int permission = ContextCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(this, PERMISSIONS,1);
        }
        ButterKnife.bind(this);
        rxPermissions = new RxPermissions(this);
        rvZhizuo.setOnClickListener(this);
        rvShenqi.setOnClickListener(this);
        rvCenter.setOnClickListener(this);
        myViewpager.setOnPageChangeListener(new MyPagerChangeListener());
        initData();
        firstRun();
//        checkNews(); //版本更新
    }

    private void initData() {
        list = new ArrayList<>();
        list.add(new MakeFragment());
//        list.add(new ShenqiFragment());
        list.add(new CenterFragment());
        adapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), list);
        myViewpager.setAdapter(adapter);
        myViewpager.setCurrentItem(0);
    }
    private void firstRun() {
        SharedPreferences sharedPreferences = getSharedPreferences("FirstRun", 0);
        Boolean first_run = sharedPreferences.getBoolean("First", true);
        if (first_run) {
            sharedPreferences.edit().putBoolean("First", false).commit();
            NumBean user = new NumBean();
            user.setNum(0);
            user.save();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rv_zhizuo:
                myViewpager.setCurrentItem(0);
                imgZhizuo.setImageResource(R.mipmap.shouye_xuanzhong);
                txtzZhizuo.setTextColor(getResources().getColor(R.color.index_textColor));
//                imgShenqi.setImageResource(R.mipmap.icon_huise_shenqi);
                txtShenqi.setTextColor(getResources().getColor(R.color.index_textColor_hui));
                imgCenter.setImageResource(R.mipmap.wode_weixuanzhong);
                txtCenter.setTextColor(getResources().getColor(R.color.index_textColor_hui));
                break;
            case R.id.rv_center:
                myViewpager.setCurrentItem(1);
                imgZhizuo.setImageResource(R.mipmap.shouye);
                txtzZhizuo.setTextColor(getResources().getColor(R.color.index_textColor_hui));
//                imgShenqi.setImageResource(R.mipmap.icon_huise_shenqi);
                txtShenqi.setTextColor(getResources().getColor(R.color.index_textColor_hui));
                imgCenter.setImageResource(R.mipmap.wode_xuanzhong);
                txtCenter.setTextColor(getResources().getColor(R.color.index_textColor));
                break;
            case R.id.rv_shenqi:
                rxPermissions.request(Manifest.permission.CAMERA)
                        .subscribe(granted -> {
                            if (granted) { // Always true pre-M
                                //如果已经授权就直接跳转到二维码扫面界面
                                Intent intent = new Intent(IndexMainActivity.this,
                                        CaptureActivity.class);
                                startActivity(intent);
                                Toast.makeText(this, "扫一扫", Toast.LENGTH_SHORT).show();
                            } else { // Oups permission denied
                                Toast.makeText(this, "相机权限被拒绝，无法扫描二维码", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        });
                break;
            default:
                break;
        }
    }


    /**
     * 设置一个ViewPager的侦听事件，当左右滑动ViewPager时菜单栏被选中状态跟着改变
     */
    public class MyPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    myViewpager.setCurrentItem(0);
                    imgZhizuo.setImageResource(R.mipmap.shouye_xuanzhong);
                    txtzZhizuo.setTextColor(getResources().getColor(R.color.index_textColor));
//                    imgShenqi.setImageResource(R.mipmap.icon_huise_shenqi);
                    txtShenqi.setTextColor(getResources().getColor(R.color.index_textColor_hui));
                    imgCenter.setImageResource(R.mipmap.wode_weixuanzhong);
                    txtCenter.setTextColor(getResources().getColor(R.color.index_textColor_hui));
                    break;
//                case 1:
//                    myViewpager.setCurrentItem(1);
////                    imgZhizuo.setImageResource(R.mipmap.icon_huise_shouye);
//                    txtzZhizuo.setTextColor(getResources().getColor(R.color.index_textColor_hui));
////                    imgShenqi.setImageResource(R.mipmap.icon_heise_shenqi);
//                    txtShenqi.setTextColor(getResources().getColor(R.color.index_textColor));
////                    imgCenter.setImageResource(R.mipmap.icon_huiise_gerenzhongxin);
//                    txtCenter.setTextColor(getResources().getColor(R.color.index_textColor_hui));
//                    break;
                case 1:
                    myViewpager.setCurrentItem(1);
                    imgZhizuo.setImageResource(R.mipmap.shouye);
                    txtzZhizuo.setTextColor(getResources().getColor(R.color.index_textColor_hui));
//                    imgShenqi.setImageResource(R.mipmap.icon_huise_shenqi);
                    txtShenqi.setTextColor(getResources().getColor(R.color.index_textColor_hui));
                    imgCenter.setImageResource(R.mipmap.wode_xuanzhong);
                    txtCenter.setTextColor(getResources().getColor(R.color.index_textColor));
                    break;
                default:
                    break;

            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                ToastUtils.showShortToast("再按一次退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //版本更新提醒
    public void checkNews() {
        HttpUtils.getInstance().postNews(new BaseCallback<GetNewBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @Override
            public void onSuccess(Response response, GetNewBean o) {
                if (response.isSuccessful() && o != null && o.isHasnew()) {
                    DialogDownLoadAPK loadAPK = new DialogDownLoadAPK(IndexMainActivity.this, "发现新版本，" + o.getVername() + "来啦");
                    loadAPK.show();
                    loadAPK.setOnClickListener(clicked -> {
                        if (clicked) {
                            openActionView(o.getDownurl());
                        }
                    });
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }
}
